<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\Offline;
use App\Models\AuditingLog;
use App\Models\BookInfo;
use App\Models\File;
use App\Models\Product;
use App\Models\ProductInfo;
use App\Models\Resource;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use App\Models\AdminUser;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Ramsey\Uuid\Uuid;

class ProductController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header('产品管理');
            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('产品管理');
//            $content->description('description');

            $content->body($this->form($id)->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('产品管理');
//            $content->description('');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid($status = null)
    {
        $token = csrf_token();
        Admin::script("auditingLoad('$token'); popverLoad()");
        return Admin::grid(Product::class, function (Grid $grid) use ($status) {

            $grid->id('ID');
            $grid->model()->orderBy('id', 'desc');
            $grid->disableExport();
            if ($status)
            {
                $grid->model()->where('auditing_status', $status);
                $grid->disableCreateButton();
                $grid->disableActions();
            }

            $grid->column('name', '产品名字')->display(function ($value) {
                return $value . '&nbsp;&nbsp;<a class="layui-btn" target="_blank"  href="' . route('product.preview', ['uuid' => $this->uuid]) . '">预览详情</a>';
            });
            $grid->column('cover', '书本介绍图')->display(function ($value) {

                if ($value && count($value) > 0) {

                    $url = asset('uploads/' . $value[0]);

                    return '
                        <a class="layui-btn layui-btn-primary product-popver" href="javascript:;" src-data="' . $url . '">预览</a>
                    ';
                }
                return '';
            });

            $grid->resources('其他分类')->pluck('name')->map('ucwords')->implode('、');

            $grid->column('try', '试读')->display(function () {
                $try = '';
                $tryout = $this->files()
                    ->select('id', 'product_id', 'tryout', 'category', 'external')
                    ->orderBy('created_at', 'asc')
                    ->whereNotNull('tryout')
                    ->whereIn('category', ['video', 'audio'])
                    ->groupBy('category')
                    ->get();

                if ($tryout)
                {
                    foreach ($tryout as $key => $item)
                    {
                        if ($key != 0)
                            $try .= '&nbsp;';

                        if ($item->tryout)
                        {
                            $url = asset('uploads/' . $item->tryout);
                        } else {
                            $url = $item->external;
                        }

                        if ($item->category == 'video')
                        {
                            $try .= '<a href="'. $url .'" target="_blank">视频</a>';
                        } else {
                            $try .= '<a href="'. $url .'" target="_blank">音频</a>';
                        }
                    }
                }
                return $try;
            });

            $grid->column('created_at', '添加时间');
            $grid->admin_id('添加人')->display(function($adminId) {

                $admin = AdminUser::find($adminId);

                if (!$admin)
                    return '<span style="color: red">数据错误</span>';

                return $admin->name;
            });

            $grid->column('auditing_status', '审核状态')->display(function ($value) {
                $statusArr = [
                    'one' => '一审',
                    'two' => '二审',
                    'three' => '三审',
                    'online' => '上线',
                    'offline' => '下线'
                ];

                if (!array_key_exists($value, $statusArr))
                    return $value;

                return $statusArr[$value];
            });
            $states = [
                'on'  => ['value' => '1', 'text' => '打开', 'color' => 'success'],
                'off' => ['value' => '0', 'text' => '关闭', 'color' => 'danger'],
            ];
            $grid->is_new('NEW标签')->switch($states);
            if ($status && $status != 'online' && $status != 'offline')
            {
                $grid->column('auditing', '审核')->display(function ()  use ($status) {

                    $rejectStr = $status == 'one' ? '删除' : '驳回';

                    $html = '<a class="layui-btn layui-btn-primary auditing" data-auditing-id="'. $this->id . '" data-auditing-process="' . $this->auditing_status .
                        '" data-auditing-operating="reject" href="javascript:;" >' . $rejectStr . '</a>&nbsp;&nbsp;';
                    if ($status == 'one') {
                        $html .= '<a class="layui-btn layui-btn-primary auditing" data-auditing-id="'. $this->id . '" data-auditing-process="' . $this->auditing_status .
                            '" data-auditing-operating="agree" href="javascript:;" >提交二审</a>';
                    } elseif ($status == 'two') {
                        $html .= '<a class="layui-btn layui-btn-primary auditing" data-auditing-id="'. $this->id . '" data-auditing-process="' . $this->auditing_status .
                            '" data-auditing-operating="agree" href="javascript:;" >提交三审</a>';
                    } elseif ($status == 'three') {
                        $html .= '<a class="layui-btn layui-btn-primary auditing" data-auditing-id="'. $this->id . '" data-auditing-process="' . $this->auditing_status .
                            '" data-auditing-operating="agree" href="javascript:;" >上线</a>';
                    }

                    return $html;
                });
            }

            $grid->actions(function (Grid\Displayers\Actions $actions) use($status) {
                $row = $actions->row;
                if ($row->auditing_status == 'online')
                    $actions->append(new Offline($actions->getKey()));

                if ($row->auditing_status != 'offline' && $row->auditing_status != 'one')
                {
                    $actions->disableEdit();
                    $actions->disableDelete();
                }

            });

            $grid->filter(function ($filter) use ($status) {
                $filter->disableIdFilter();
                $filter->like('name', '书籍名字');
                $category = Category::selectOptions();
                unset($category[0]);
                $filter->in('category_id', '分类')->multipleSelect($category);

                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('resources', function ($query) use ($input)
                    {
                        $query->whereIn('resource_id', $input);
                        $query->select('product_resources.id', 'product_id', 'resource_id');
                    });
                    $query->select('id');
                }, '其他分类')
                    ->checkbox(Resource::all()->pluck('name', 'id'));

                $status = [
                    'one' => '一审',
                    'two' => '二审',
                    'three' => '三审',
                    'online' => '上线',
                    'offline' => '下线'
                ];
                $filter->in('auditing_status', '审核状态')->multipleSelect($status);

                $filter->between('created_at', '添加时间')->datetime();
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($id = null)
    {
        set_time_limit(600);

        return Admin::form(Product::class, function (Form $form) use($id) {

            $form->tab('书本介绍', function (Form $form) {

                $form->text('name', trans('admin.title'))
                    ->attribute('maxlength', '60')
                    ->help('最大长度60个字')
                    ->rules('required|max:60');

                $states = [
                    'on'  => ['value' => '1', 'text' => '打开', 'color' => 'success'],
                    'off' => ['value' => '0', 'text' => '关闭', 'color' => 'danger'],
                ];
                $form->switch('is_new', 'NEW标签')->default('off')->states($states);

                $form->text('summary', '书籍推荐短语')
                    ->help('短语建议长度：不超过50个中文，英文20个单词内。')
                    ->rules('required');

                $form->multipleImage('cover', '书本介绍图')
                    ->removable()
                    ->uniqueName()
                    ->attribute('accept', 'image/png, image/jpeg, image/jpg')
                    ->help('图片不大于500kb,推荐尺寸：256 * 366, 支持格式：png、jpeg、jpg. 如有多张图片请一次性选择！')
                    ->rules('required|image|max:500', [
                        'max' => '封面图片最大值为500kb'
                    ]);

                $form->editor('introduce', '内容简介');
                $form->editor('recommend', '编辑推荐');

                $form->text('author', '作者');
                $form->textarea('author_about', '作者简介');

                $form->text('press', '出版单位')
                    ->attribute('maxlength', '60')
                    ->help('最大长度60个字符')
                    ->rules('required|max:60');

            })->tab('书本分类', function (Form $form) use($id) {

                $form->select('category_id', '导航分类')
                    ->options(Category::selectOptions())
                    ->load('categorys', '/admin/categoryList')
                    ->help('如更改导航分类请从新选择关联属性')
                    ->rules('required');

                $cat = Category::all();
                if ($id) {
                    $pro = Product::select('id', 'category_id')->find($id);
                    $datas = (new Controller())->getMenuTree($cat->toArray(), $pro->category_id);
                    $cat = [];
                    foreach ($datas as $data) {
                        $cat[$data['id']] = $data['name'];
                    }
                } else {
                    $cat = $cat->pluck('name', 'id');
                }

                $form->multipleSelect('categorys', '关联属性')
                    ->options($cat);

                $form->checkbox('resources', '其他分类')
                    ->options(Resource::where('status', 'enabled')->get()->pluck('name', 'id'));
            })->tab('试读内容', function (Form $form) {

                $form->multipleImage('pictures', '书籍试读')
                    ->help('图片不大于5mb,如有多张图片请一次性选择！支持格式：png、jpeg、jpg')
                    ->attribute('accept', 'image/png, image/jpeg, image/jpg')
                    ->placeholder('图片超过5mb')
                    ->uniqueName()
                    ->removable()
                    ->rules('image|max:5120');

            })->tab('详细信息', function (Form $form) {

                $form->text('details.grade', '适用年龄段'); //原为适用年级
//                $form->text('details.upc', '商品编码');  //去除商品编码，屏蔽不删除， 避免后期再加上
                $form->number('details.pages', '页数');
                $form->date('details.date', '出版日期')
                    ->placeholder('输入出版日期');
                $form->text('details.isbn', 'ISBN');
                $form->text('details.package', '包装（开发者）')
                    ->help('游戏产品填写开发者');
                $form->text('details.format', '开本（类型）')
                    ->help('游戏产品填写类型');
                $form->text('details.material', '用纸（出版社）')
                    ->help('游戏产品填写出版社');
                $form->currency('details.priced', '定价');
                $form->switch('details.is_game', '游戏产品')->default('off')
                    ->states([
                        'on'  => ['value' => '1', 'text' => '是', 'color' => 'success'],
                        'off' => ['value' => '0', 'text' => '否', 'color' => 'danger'],
                    ]);

            })->tab('购买信息', function (Form $form) {
                $form->text('buy_link', '购买链接');
                $form->text('remark','备注');
                $form->hidden('admin_id')->value(Admin::user()->id);
                $form->hidden('uuid')->value(Uuid::uuid1()->toString());
                $form->switch('buy_switch', '允许购买')->default('on')->states([
                    'on'  => ['value' => '1', 'text' => '是', 'color' => 'success'],
                    'off' => ['value' => '0', 'text' => '否', 'color' => 'danger'],
                ]);
            });

            //保存后将category_id追加保存到product_categorys关联表中
            $form->saved(function (Form $form) {
                $category_id = $form->model()->category_id;
                $product = Product::where('id', $form->model()->id)
                    ->select('id', 'auditing_status')
                    ->first();
                if (!$product->categorys()->find($category_id))
                {
                    $product->categorys()->attach($category_id);
                }
                if ($product->auditing_status == 'offline') {
                    $product->auditing_status = 'one';
                    $product->save();
                }
            });
        });
    }

    public function cat($id)
    {
        $category = Category::select('id', 'p_id', 'level')->find($id);

        if (!$category)
        {
            $files = Category::where('p_id', $id)
                ->paginate(null, ['id', 'name as text']);

            return $files;
        }

        if ($category->level == 1)
        {
            $categoryObj = Category::whereIn('p_id', $category->children()->pluck('id'));
        } else {
            $categoryObj = Category::where('p_id', $category->id);
        }

        $category = $categoryObj->with(['children' => function($q) {
            $q->select('id', 'p_id', 'level');
        }])
            ->whereHas('children', function (){})
            ->get(['id', 'p_id', 'level']);

        $children = array_pluck($category->toArray(), 'children');
        $levelFour = [];
        foreach ($children as $key => $child)
        {
            $levelFour = array_merge(array_pluck($child, 'id'));
        }

        $files = Category::whereIn('p_id', $levelFour)->get(['id', 'name as text']);

        return $files;
    }


    public function auditingOne()
    {
        return Admin::content(function (Content $content) {
            $content->header('产品审核：一审');
            $content->body($this->grid('one'));
        });
    }

    public function auditingTwo()
    {
        return Admin::content(function (Content $content) {
            $content->header('产品审核：二审');
            $content->body($this->grid('two'));
        });
    }

    public function auditingThree()
    {
        return Admin::content(function (Content $content) {
            $content->header('产品审核：三审');
            $content->body($this->grid('three'));
        });
    }

    public function postAuditing(Request $request)
    {
        $operating = $request->input('operating');
        $productId = $request->input('product_id');
        $process = $request->input('process');

        if (!in_array($operating, ['reject', 'agree']))
            return json_encode(['status' => 'error', 'msg' => '操作错误！']);

        $product = Product::select('id', 'auditing_status')->find($productId);
        if (!$product)
            return json_encode(['status' => 'error', 'msg' => '产品不存在！']);

        if ($process != 'offline' && $product->auditing_status != $process)
            return json_encode(['status' => 'error', 'msg' => '审核流程错误']);

        $description = $operating == 'reject' ? '驳回' : '通过';

        $statusArr = [
            'one' => '一审提交',
            'two' => '二审提交',
            'three' => '三审上线',
            'offline' => '产品下线'
        ];

        $log = new AuditingLog;
        $log->product_id = $productId;
        $log->admin_id = Admin::user()->id;
        $log->description = $statusArr[$process] . $description;
        $log->options = $operating;
        $log->save();

        if ($operating == 'reject')
        {
            if ($process == 'one') {
                $product->delete();
            } else {
                $rejectArr = [
                    'two' => 'one',
                    'three' => 'two',
                ];
                $product->auditing_status = $rejectArr[$process];
                $product->save();
            }
        } else {
            $agreeArr = [
                'one' => 'two',
                'two' => 'three',
                'three' => 'online',
                'offline' => 'offline'
            ];
            $product->auditing_status = $agreeArr[$process];
            $product->save();
        }
        admin_toastr('操作成功');
        return json_encode(['status' => 'success', 'msg' => '操作成功']);
    }


    public function preview($uuid)
    {
        $product = Product::select('id', 'uuid', 'category_id', 'name', 'summary', 'cover', 'press', 'pictures',
            'buy_link', 'author', 'author_about', 'introduce', 'remark', 'recommend')
            ->where('uuid', $uuid)
            ->first();

        if (!$product)
            return redirect('pageerror');

        $product = $product->load(
            [
                'details' => function ($query) {
                    $query->select('product_id', 'grade', 'upc', 'pages', 'date', 'isbn', 'package', 'format', 'material', 'priced');
                },
                'resources' => function ($query) {
                    $query->select('name', 'icon_url');
                },
                'files' => function ($query) {
                    $query->select('id', 'product_id', 'title', 'tryout', 'category', 'external', 'cover', 'local')
                        ->where(function ($q) {
                            $q->whereNotNull('tryout')
                                ->orWhereNotNull('external');
                        })
                        ->orderBy('created_at', 'asc')
                        ->whereIn('category', ['video', 'audio'])

                        ->groupBy('category')
                        ->get();
                }
            ]
        );

        foreach ($product->resources as $key => $resource)
        {
            unset($resource->pivot);
            $product->resources[$key] = $resource;
        }

        $product->tryout_video = null;
        $product->tryout_audio = null;
        if ($product->files)
        {
            foreach ($product->files as $key => $file)
            {
                if ($file->category == 'video')
                {
                    $product->tryout_video = $file;
                } else {
                    $product->tryout_audio = $file;
                }
            }
            unset($product->files);
        }
        $sameGradeBooks = false;

        $category = Category::select('id', 'name', 'p_id', 'level')->find($product->category_id);

        $categoryNav = [];
        if ($category)
        {
            if ($category->level == 1)
            {
                $category = $category->children()->pluck('id');
                $category = Category::whereIn('p_id', $category)->where('name', 'like', '%阶段%')->first();
            } else {
                $category = $category->children()->where('name', 'like', '%阶段%')->first();
            }

            $intersectArr = [];
            if (isset($category->children) && count($category->children)) {
                $categoryIds = $category->children->pluck('id');
                $geadeIds = Category::whereIn('p_id', $categoryIds)->pluck('id')->toArray();
                $productCatrgory = $product->categorys->pluck('id')->toArray();
                $intersectArr = array_intersect($geadeIds, $productCatrgory);
            }
            if (count($intersectArr) > 0)
            {
                $sameGradeBooks = Product::select('id', 'uuid', 'name', 'cover')
                    ->whereHas('categorys', function ($q) use($intersectArr) {
                        $q->whereIn('category_id', $intersectArr);
                    })
                    ->where('auditing_status', 'online')
                    ->where('id', '<>', $product->id)
                    ->inRandomOrder()
                    ->take(10)
                    ->get();

                foreach ($sameGradeBooks as $key => $value)
                {
                    unset($sameGradeBooks[$key]->id);
                }
                if (count($sameGradeBooks) <= 0)
                    $sameGradeBooks = false;

            }
            $categoryNav = (new \App\Http\Controllers\ProductController())->getCategoryNav($product->category_id);
        }

        return view('product.detail',
            [
                'product' => $product,
                'categoryNav' => $categoryNav,
                'sameGradeBooks' => $sameGradeBooks
            ]
        );
    }
}
